import React,{Component} from 'react'
import {connect} from 'dva'
import 'antd-mobile/dist/antd-mobile.css'
import {List, Badge} from 'antd-mobile'

class Msg extends Component{
    constructor(){
        super();
    }
    componentDidMount(){
        //this.props.dispatch({type:'user/getAllUser'})
    }
    getLastMag(arr){
        return arr[arr.length-1]
    }
    render(){
        const msgGroup = {};
        this.props.chatMsg.forEach(v=>{
            msgGroup[v.chatid] = msgGroup[v.chatid] || [];
            msgGroup[v.chatid].push(v);
        });
        for(var key in msgGroup){
            if(key.indexOf(this.props.user_id)==-1){
                delete msgGroup[key];
            }
        }
        var chatList = Object.values(msgGroup);
        //console.log(chatList);
        //console.log(msgGroup);
        return(
            <React.Fragment>
                {
                    chatList.map((item)=>{
                        var lastMsgObj = this.getLastMag(item);
                        const targetId = lastMsgObj.from === this.props.user_id?lastMsgObj.to:lastMsgObj.from
                        var unread = item.filter(item=>!item.read&&item.to==this.props.user_id).length;
                        //console.log(this.props.userList);
                        //console.log(this.props.userList);
                        //var userObj = this.props.userList.find((v)=>v._id === targetId);
                       // console.log(userObj);
                        return (
                        <List key={item}>
                            <List.Item
                            extra = {<Badge text={unread}></Badge>}
                            arrow='horizontal'
                            onClick={()=>{
                                this.props.history.push(`/chat/${targetId}`);
                            }}
                            >
                                {lastMsgObj.content}
                                <List.Item.Brief></List.Item.Brief>
                            </List.Item>
                        </List>
                        )
                    })
                }
            </React.Fragment>
        )
    }

}
const mapStateProps = (state)=>{
    return{
       chatMsg:state.chat.chatMsg,
       user_id:state.user.user_id,
       userList:state.user.userList
    }
}
export default connect(mapStateProps)(Msg);